<template>
  <yd-layout>
    <yd-navbar slot="navbar" title="我要预订" fixed>
      <router-link to="/hello" slot="left">
        <yd-navbar-back-icon></yd-navbar-back-icon>
      </router-link>
      <yd-button type="hollow" :disabled="sureState" slot="right" @click.native="subBook">确定</yd-button>
    </yd-navbar>
    <div style="margin-top: 50px;">

      <mt-cell title="选择日期" :value="getFormatDate" @click.native="$refs.picker.open()"></mt-cell>
      <mt-datetime-picker ref="picker" 
      	v-model="daySelect" type="date" 
      	year-format="{value}年" month-format="{value}月" date-format="{value}日"
      	@confirm="func"
      	:startDate="daytoday"
      	>
      </mt-datetime-picker>
    </div>
    <div>

      <mt-navbar v-model="weekNow">
        <mt-tab-item :id="index" v-for="(item,index) in weekList" :key="item.toString()">{{item}}</mt-tab-item>
      </mt-navbar>
      <!-- tab-container -->
      <mt-tab-container v-model="weekNow">
        <mt-tab-container-item :id="index" v-for="(item,index) in weekList" :key="item.toString()">

          <yd-timeline>
            <yd-timeline-item v-for="(i,dex) in data[index].timer" :key="item.toString()+i.toString()">
              <p>{{i.timeLine}}
                <font v-if="i.doing == '暂无' || i.doing == '预订'" style="float: right;">
                  <yd-button v-if="i.doing == '暂无'" type="hollow" @click.native="makeBook(i,index,dex)">预订</yd-button>
                  <yd-button v-else type="primary" @click.native="makeBook(i,index,dex)">预订</yd-button>
                </font>
                <font v-else>
                  {{i.doing}}
                  <span v-if="me.openId === i.openId" style="float: right">您已预订该时间段</span>
                </font>
              </p>
            </yd-timeline-item>
          </yd-timeline>

        </mt-tab-container-item>

      </mt-tab-container>

    </div>

    <yd-popup v-model="sureBtn" position="center" width="90%">
      <yd-cell-group>
        <yd-cell-item>
          <span slot="left">日期：{{form.date}}</span>
        </yd-cell-item>
        <yd-cell-item>
          <span slot="left">时间：{{form.time}}</span>
        </yd-cell-item>
        <yd-cell-item>
          <span slot="left">预订人：{{me.real_name}}</span>
        </yd-cell-item>
        <yd-cell-item>
          <span slot="left">目的：</span>
          <yd-input slot="right" v-model="form.bookReason" max="128" required :showRequiredIcon="true" placeholder="预定会议室的目的"></yd-input>
        </yd-cell-item>
      </yd-cell-group>
      <yd-button size="large" type="primary" @click.native="bookMeeting">提交</yd-button>
    </yd-popup>
  </yd-layout>
</template>

<script>
  import bookApi from '@/api/bookApi.js'
  import { mapState, mapMutations } from 'vuex'
  import userApi from '@/api/userApi'

  export default {
    computed: {
      ...mapState([
        'me'
      ]),
      getFormatDate() {
        if(this.daySelect == null)
          this.daySelect = new Date()
        return this.daySelect.Format("yyyy-MM-dd");
      }
    },
    data() {
      return {
      	daytoday: new Date(),
        sureState: true,
        weekNow: "",
        timeSelect: [],
        startDate: new Date(),
        daySelect: null,
        firstDay: new Date(),
        form: {
          date: '',
          time: '',
          week: '',
          bookReason: ''
        },
        query: {
          date: ''
        },
        sureBtn: false,
        data: [{
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }, {
          label: "",
          timer: [{
            timeLine: '09:00-09:30',
            doing: '暂无'
          }]
        }],
        weekList: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        emptyList: [{
          timeLine: '09:00-09:30',
          doing: '暂无'
        }, {
          timeLine: '09:30-10:00',
          doing: '暂无'
        }, {
          timeLine: '10:00-10:30',
          doing: '暂无'
        }, {
          timeLine: '10:30-11:00',
          doing: '暂无'
        }, {
          timeLine: '11:00-11:30',
          doing: '暂无'
        }, {
          timeLine: '11:30-12:00',
          doing: '暂无'
        }, {
          timeLine: '12:00-12:30',
          doing: '暂无'
        }, {
          timeLine: '12:30-13:00',
          doing: '暂无'
        }, {
          timeLine: '13:00-13:30',
          doing: '暂无'
        }, {
          timeLine: '13:30-14:00',
          doing: '暂无'
        }, {
          timeLine: '14:00-14:30',
          doing: '暂无'
        }, {
          timeLine: '14:30-15:00',
          doing: '暂无'
        }, {
          timeLine: '15:00-15:30',
          doing: '暂无'
        }, {
          timeLine: '15:30-16:00',
          doing: '暂无'
        }, {
          timeLine: '16:00-16:30',
          doing: '暂无'
        }, {
          timeLine: '16:30-17:00',
          doing: '暂无'
        }, {
          timeLine: '17:00-17:30',
          doing: '暂无'
        }, {
          timeLine: '17:30-18:00',
          doing: '暂无'
        }]
      }
    },
    methods: {
      ...mapMutations([
        'updateMe'
      ]),
      showErrMsg(msg){
        return msg.split(': ')[1];
      },
      bookMeeting() {
        if(this.form.bookReason == '') {
          this.$dialog.toast({
            mes: '请填写预订目的！',
            timeout: 1000,
            icon: 'error',
            callback: () => {}
          })
        } else {
          var vm = this
          bookApi.bookBook(this.form)
            .then(data => {
              if(data == '预定成功') {
                this.$dialog.toast({
                  mes: '预定申请成功!请等待审批!',
                  timeout: 1000,
                  icon: 'success',
                  callback: () => {
                    vm.$router.push('/hello')
                  }
                })

              } else {
                this.$dialog.toast({
                  mes: '预定失败！请重试!',
                  timeout: 1000,
                  icon: 'error',
                  callback: () => {}
                })
              }
            })
            .catch(error => {
              console.log(error)
              this.$dialog.toast({
                mes: this.showErrMsg(error.errMsg),
                timeout: 1000,
                icon: 'error',
                callback: () => {}
              })
            })
        }
      },
      subBook() {
        if(this.timeSelect.length && this.timeSelect.length > 0) {
          this.sureBtn = true
          this.form.time = this.timeSelect[0].toString()
            .split('-')[0] + '-' + this.timeSelect[this.timeSelect.length - 1].toString()
            .split('-')[1]
        }
      },
      addSelect(timeLine) {
        if(this.timeSelect.length == 0) {
          this.timeSelect.push(timeLine)
          return true
        }
        var t = this.timeSelect[this.timeSelect.length - 1].toString()
          .split('-')[1]
        if(t == timeLine.toString()
          .split('-')[0]) {
          this.timeSelect.push(timeLine)
          return true
        } else {
          return false
        }
      },
      removeSelect(timeLine, index, dex) {
        var temp = 0
        for(var i = 0; i < this.timeSelect.length; i++) {
          if(timeLine == this.timeSelect[i]) {
            temp = i
          }
        }
        var timeSelect = []
        for(var i = 0; i < temp; i++) {
          timeSelect.push(this.timeSelect[i])
        }
        for(var i = 0; i < this.data[index].timer.length; i++) {
          if(this.data[index].timer[i].doing == '预订' || this.data[index].timer[i].doing == '暂无') {
            if(i < dex && this.data[index].timer[i].doing == '预订') {
              this.data[index].timer[i].doing = '预订'
            } else {
              this.data[index].timer[i].doing = '暂无'
            }
          }
        }
        this.timeSelect = timeSelect
      },
      makeBook(temp, index, dex) {
        if(temp.doing == '预订') {
          this.removeSelect(temp.timeLine, index, dex)
        } else {
          if(this.addSelect(temp.timeLine)) {
            temp.doing = '预订'
          } else {
            this.$dialog.toast({
              mes: '请选择连续的时间段！',
              timeout: 1000,
              icon: 'error',
              callback: () => {}
            })
          }
        }
      },
      loadWeek() {
        var vm = this
        bookApi.findBooks(this.query)
          .then(data => {
            console.log(data)
            vm.data = []
            for(var i = 0; i < data.length; i++) {
              var temp = {
                label: vm.weekList[i],
                timer: []
              }
              if(!data[i].timer || data[i].timer == '' || (data[i].timer.length && data[i].timer.length == 0)) {
                temp.timer = vm.emptyList
              } else {
                temp.timer = data[i].timer
              }
              vm.data.push(temp)
            }
          })
          .catch(err => {})
      },
      func() {
        let curVal = this.getFormatDate
        this.query.date = curVal
        var dateNow = this.daySelect
        this.form.week = dateNow.WeekDay()
        var day = dateNow.getDay() || 7
        this.weekNow = day-1
        this.firstDay = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() + 1 - day)
        this.loadWeek()
      }
    },
    mounted() {
      console.log(this.me)
      var d = new Date()
      this.func()
      this.query.date = this.getFormatDate
      if(!sessionStorage.getItem('token')) {
        this.$router.push('/login')
      }
      var token = sessionStorage.getItem('token')
      if(token && !this.me.role) {
        // 获取当前用户信息
        userApi.me()
          .then(data => {
            this.updateMe(data)
          })
          .catch(errMsg => {})
      }
      var vm = this
    },
    watch: {
   /*   'getFormatDate': function(curVal, oldVal) {
        this.query.date = curVal
        this.loadWeek()
        var dateNow = new Date(curVal.replace('-', '/'))
        this.form.week = dateNow.WeekDay()
        this.weekNow = dateNow.getDay() || 7
        this.firstDay = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() + 1 - this.weekNow)
      },*/
      'timeSelect': {
        handler(curVal, oldVal) {
          if(this.timeSelect.length == 0) {
            this.sureState = true
          } else {
            this.sureState = false
          }
        },
        deep: true
      },
      'weekNow': function(curVal, oldVal) {
        var dateNow = this.firstDay
        this.form.date = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate() + curVal)
          .Format('yyyy-MM-dd')
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>